package com.swak.frame.job;


import com.alibaba.fastjson.JSON;
import com.swak.frame.common.SpringBeanFactory;
import com.swak.frame.dto.Result;
import com.swak.frame.job.annotation.EasyJobInfo;
import com.swak.frame.util.GetterUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * The type Easy job trigger.
 *
 * @author: yuanchao.ma
 * @since 2022 /8/24 15:49
 */
@Slf4j
public class EasyJobTrigger {

    private final JobScheduleHandler jobScheduleHandler;

    public EasyJobTrigger(JobScheduleHandler jobScheduleHandler) {
        this.jobScheduleHandler = jobScheduleHandler;
    }
    /**
     * Process trigger.
     *
     * @param jobInfo the job info
     */
    public  void processTrigger(EasyJobInfo jobInfo) {
        Boolean enabled = jobScheduleHandler.resolveExpressionAsBoolean(jobInfo.getScheduleEnabled());
        if(!Optional.ofNullable(enabled).orElse(true)) {
            log.debug("[easy-job]#任务调度未开启，jobName:{}",jobInfo.getJobName());
            return;
        }
        EasyJobHandler easyJobHandler =  SpringBeanFactory.getBean(jobInfo.getExecutorHandler(), EasyJobHandler.class);
        if(easyJobHandler!=null) {
            EasyJobContext context = EasyJobContext.builder()
                    .executorHandler(easyJobHandler)
                    .jobName(jobInfo.getJobName())
                    .params(GetterUtil.getSplitStr(jobInfo.getExecutorParam()))
                    .shardingCount(jobInfo.getShardingCount())
                    .shardingNum(jobInfo.getShardingNum())
                    .scheduleConf(jobInfo.getScheduleConf())
                    .scheduleType(jobInfo.getScheduleType()).build();
            Result<Void> response = easyJobHandler.execute(context);
           if(!response.isSuccess()) {
               log.warn("easy-job execute error,jobName:{},context:{}", jobInfo.getJobName(), JSON.toJSONString(context));
           }
        }
    }
}
